//
//  RegistViewController.m
//  PropertyManager
//
//  Created by TNG on 2018/7/11.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "RegistViewController.h"

@interface RegistViewController ()

@property (strong, nonatomic) UIScrollView * sc;
@property (strong, nonatomic) UIImageView * img;
@property (strong, nonatomic) UITextField * phoneTextFiled;
@property (strong, nonatomic) UITextField * codeTextFiled;
@property (strong, nonatomic) UITextField * pwdTextFiled;
@property (strong, nonatomic) UIButton * codeBtn;
@property (strong, nonatomic) UIButton * registBtn;
@property (assign, nonatomic) int  time;
@property (strong, nonatomic) NSTimer * timer;
@property (strong, nonatomic) UIView * lineView;
@property (strong, nonatomic) UIView * lineView1;
@property (strong, nonatomic) UIView * lineView2;
@property (strong, nonatomic) UITextField * IDTextFiled;
@property (strong, nonatomic) UITextField * nameTextFiled;
@property (strong, nonatomic) UIView * lineView3;
@property (strong, nonatomic) UIView * lineView4;
@property (strong, nonatomic) UIButton * backBtn;

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.time = 60;
    [self.view addSubview:self.sc];
    [self.sc addSubview:self.backBtn];
    [self.sc addSubview:self.img];
    [self.sc addSubview:self.phoneTextFiled];
    [self.sc addSubview:self.lineView];
    [self.sc addSubview:self.codeTextFiled];
    [self.sc addSubview:self.codeBtn];
    [self.sc addSubview:self.lineView1];
    [self.sc addSubview:self.nameTextFiled];
    [self.sc addSubview:self.lineView2];
    [self.sc addSubview:self.IDTextFiled];
    [self.sc addSubview:self.lineView3];
    [self.sc addSubview:self.pwdTextFiled];
    [self.sc addSubview:self.lineView4];
    [self.sc addSubview:self.registBtn];
    self.sc.contentSize = CGSizeMake(WIDTH,CGRectGetMaxY(self.registBtn.frame) + 60);
}

-(UIScrollView *)sc
{
    if (_sc == nil) {
        _sc = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - kHomeLineH)];
        _sc.showsVerticalScrollIndicator = NO;
        _sc.showsHorizontalScrollIndicator = NO;
        _sc.pagingEnabled = YES;
        _sc.bounces = NO;
    }
    return _sc;
}

-(UIButton *)backBtn
{
    if (_backBtn == nil) {
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(5, kStatusBarH, 44, 44)];
        [_backBtn setImage:[UIImage imageNamed:@"backIcon"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}


-(void)backBtnClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(UIImageView *)img
{
    if (_img == nil) {
        _img = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH/2 - 17, 0 + 50, 57, 57)];
        _img.contentMode = UIViewContentModeScaleAspectFill;
        _img.clipsToBounds = YES;
        _img.image  = [UIImage imageNamed:@"logo"];
    }
    return _img;
}

-(UITextField *)phoneTextFiled
{
    if (_phoneTextFiled == nil) {
        UITextField * telPhoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(45, CGRectGetMaxY(self.img.frame) + 25, WIDTH - 90, 30)];
        telPhoneTextField.placeholder = @"请输入手机号";
        telPhoneTextField.font = font(16);
        telPhoneTextField.textColor = SFMColor(51, 51, 51);
        telPhoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        telPhoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        [telPhoneTextField addTarget:self action:@selector(telPhoneTextChang) forControlEvents:UIControlEventEditingChanged];
        _phoneTextFiled = telPhoneTextField;
    }
    return _phoneTextFiled;
}

-(void)telPhoneTextChang
{
    NSString * str = _phoneTextFiled.text;
    if (str.length>11) {
        _phoneTextFiled.text = [str substringToIndex:11];
    }
}

-(UIView *)lineView
{
    if (_lineView == nil) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(42, CGRectGetMaxY(self.phoneTextFiled.frame) + 10, WIDTH - 84, 0.5)];
        _lineView.backgroundColor = SFMLineColor;
    }
    return _lineView;
}

-(UITextField *)codeTextFiled
{
    if (_codeTextFiled == nil) {
        _codeTextFiled = [[UITextField alloc]initWithFrame:CGRectMake(45, CGRectGetMaxY(self.lineView.frame) + 25, WIDTH - 200, 30)];
        _codeTextFiled.placeholder = @"请输入验证码";
        _codeTextFiled.font = font(17);
        _codeTextFiled.textColor = SFMColor(51, 51, 51);
        [_codeTextFiled addTarget:self action:@selector(codeTextFiledDidChange) forControlEvents:UIControlEventEditingChanged];
        _codeTextFiled.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _codeTextFiled;
}

-(void)codeTextFiledDidChange
{
    NSString * str = self.codeTextFiled.text;
    if (str.length > 18) {
        self.codeTextFiled.text = [str substringToIndex:18];
    }
}

-(UIView *)lineView1
{
    if (_lineView1 == nil) {
        _lineView1 = [[UIView alloc] initWithFrame:CGRectMake(42, CGRectGetMaxY(self.codeTextFiled.frame) + 10, WIDTH - 84, 0.5)];
        _lineView1.backgroundColor = SFMLineColor;
    }
    return _lineView1;
}

-(UIButton *)codeBtn
{
    if (_codeBtn == nil) {
        _codeBtn = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH - 115, CGRectGetMaxY(self.lineView.frame) + 25, 70, 30)];
        _codeBtn.titleLabel.font = font(12);
        _codeBtn.layer.cornerRadius = 15;
        [_codeBtn setTitle:@"获取" forState:UIControlStateNormal];
        [_codeBtn setBackgroundColor:SFMNavBarColor];
        [_codeBtn addTarget:self action:@selector(codeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeBtn;
}

-(UITextField *)nameTextFiled
{
    if (_nameTextFiled == nil) {
        _nameTextFiled = [[UITextField alloc]initWithFrame:CGRectMake(45, CGRectGetMaxY(self.lineView1.frame) + 25, WIDTH - 90, 30)];
        _nameTextFiled.placeholder = @"请输入真实姓名";
        _nameTextFiled.font = font(17);
        _nameTextFiled.textColor = SFMColor(51, 51, 51);
        _nameTextFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _nameTextFiled;
}

-(UIView *)lineView2
{
    if (_lineView2 == nil) {
        _lineView2 = [[UIView alloc] initWithFrame:CGRectMake(42, CGRectGetMaxY(self.nameTextFiled.frame) + 10, WIDTH - 84, 0.5)];
        _lineView2.backgroundColor = SFMLineColor;
    }
    return _lineView2;
}

-(UITextField *)IDTextFiled
{
    if (_IDTextFiled == nil) {
        _IDTextFiled = [[UITextField alloc]initWithFrame:CGRectMake(45, CGRectGetMaxY(self.lineView2.frame) + 25, WIDTH - 90, 30)];
        _IDTextFiled.placeholder = @"请输入身份证号";
        _IDTextFiled.font = font(17);
        _IDTextFiled.textColor = SFMColor(51, 51, 51);
        _IDTextFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _IDTextFiled;
}

-(UIView *)lineView3
{
    if (_lineView3 == nil) {
        _lineView3 = [[UIView alloc] initWithFrame:CGRectMake(42, CGRectGetMaxY(self.IDTextFiled.frame) + 10, WIDTH - 84, 0.5)];
        _lineView3.backgroundColor = SFMLineColor;
    }
    return _lineView3;
}

-(UITextField *)pwdTextFiled
{
    if (_pwdTextFiled == nil) {
        _pwdTextFiled = [[UITextField alloc]initWithFrame:CGRectMake(45, CGRectGetMaxY(self.lineView3.frame) + 25, WIDTH - 90, 30)];
        _pwdTextFiled.placeholder = @"请输入密码";
        _pwdTextFiled.font = font(17);
        _pwdTextFiled.textColor = SFMColor(51, 51, 51);
        _pwdTextFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_pwdTextFiled addTarget:self action:@selector(pwdTextFiledDidChange) forControlEvents:UIControlEventEditingChanged];
        _pwdTextFiled.secureTextEntry = YES;
    }
    return _pwdTextFiled;
}

-(UIView *)lineView4
{
    if (_lineView4 == nil) {
        _lineView4 = [[UIView alloc] initWithFrame:CGRectMake(42, CGRectGetMaxY(self.pwdTextFiled.frame) + 10, WIDTH - 84, 0.5)];
        _lineView4.backgroundColor = SFMLineColor;
    }
    return _lineView4;
}

-(void)pwdTextFiledDidChange
{
    NSString * str = self.pwdTextFiled.text;
    if (str.length > 18) {
        self.pwdTextFiled.text = [str substringToIndex:18];
    }
}

-(UIButton *)registBtn
{
    if (_registBtn == nil) {
        _registBtn = [[UIButton alloc] initWithFrame:CGRectMake(40, CGRectGetMaxY(self.lineView4.frame) + 37, WIDTH - 80, 50)];
        _registBtn.titleLabel.font = font(16);
        [_registBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _registBtn.layer.cornerRadius = 25;
        [_registBtn setBackgroundColor:SFMNavBarColor];
        [_registBtn addTarget:self action:@selector(registBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registBtn;
}

#pragma mark - 获取验证码
-(void)codeBtnClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    
    if (self.phoneTextFiled.text.length != 11) {
        [SVProgressHUD ShowErrorMessage:@"手机号码格式有误"];
        return;
    }
    
    if (self.time ==60)
    {
        btn.userInteractionEnabled = NO;
        
        [self creatTimer];
        
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        [params setValue:self.phoneTextFiled.text forKey:@"usernumber"];
        //（1、注册验证短信；2、资料修改短信；3、群发短信）
        [params setValue:@"1" forKey:@"type"];
        [params setValue:@"1" forKey:@"terrace"];
        [[HTTPClient shareClient] requestWithPath:@"/rest/gbSmsController" AndParams:params AndReturnBlock:^(NSDictionary *dic) {
            [SVProgressHUD ShowSuccessMessage:@"短信发送成功，请注意查收"];
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.userInteractionEnabled = YES;
            });
        }AndFailMessage:^(NSString *message, NSString *errorCode) {
            [SVProgressHUD ShowErrorMessage:message];
            btn.userInteractionEnabled = YES;
        }];
    }else
    {
        if (self.time==0) {
            btn.userInteractionEnabled = YES;
        }
    }
    
}

#pragma mark - 下一步事件
-(void)registBtnClick:(UIButton *)btn
{
    [self.view endEditing:YES];

    if (self.phoneTextFiled.text.length != 11) {
        [SVProgressHUD ShowErrorMessage:@"手机号码格式有误"];
        return;
    }
    
    if (self.codeTextFiled.text.length !=4) {
        [SVProgressHUD ShowErrorMessage:@"验证码输入不正确"];
        return;
    }
    
    if (self.pwdTextFiled.text.length>18) {
        [SVProgressHUD ShowErrorMessage:@"密码长度必须6～18位"];
        return;
    }
    
    if (self.nameTextFiled.text.length == 0) {
        [SVProgressHUD ShowErrorMessage:@"请输入真实姓名"];
        return;
    }
    
    if (self.IDTextFiled.text.length == 0) {
        [SVProgressHUD ShowErrorMessage:@"请输入身份证号"];
        return;
    }
    
    BOOL isPhone = [NSString valiMobile:self.phoneTextFiled.text];
    if (isPhone)
    {
//        if (![NSString isCorrect:self.IDTextFiled.text]) {
//            [SVProgressHUD ShowErrorMessage:@"请输入正确身份证号"];
//            return;
//        }
        btn.userInteractionEnabled = NO;
        
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        [params setValue:self.phoneTextFiled.text forKey:@"phone"];
        [params setValue:self.pwdTextFiled.text forKey:@"password"];
        [params setValue:self.codeTextFiled.text forKey:@"code"];
        [params setValue:self.IDTextFiled.text forKey:@"cid"];
        [params setValue:self.nameTextFiled.text forKey:@"realname"];

        WeakSelf;
        [[HTTPClient shareClient] requestWithPath:@"/rest/appLoginController/createAppUser" AndParams:params AndReturnBlock:^(NSDictionary *dic) {
           
            NSDictionary * userDic = dic[@"data"][@"user"];
//         1租户2工作人员
            NSString * usertype = userDic[@"usertype"];
            NSString * gbuserid = userDic[@"gbuserid"];
            NSString * username = userDic[@"username"];
            NSString * headimgurl = userDic[@"headimgurl"];
            NSString * userID = userDic[@"id"];

            [[NSUserDefaults standardUserDefaults] setValue:usertype forKey:@"usertype"];
            [[NSUserDefaults standardUserDefaults] setValue:gbuserid forKey:@"gbuserid"];
            [[NSUserDefaults standardUserDefaults] setValue:username forKey:@"loginname"];
            [[NSUserDefaults standardUserDefaults] setValue:headimgurl forKey:@"headimgurl"];
            [[NSUserDefaults standardUserDefaults] setValue:userID forKey:@"Id"];

            [[NSUserDefaults standardUserDefaults] synchronize];
            TabBarViewController * tab = [[TabBarViewController alloc] init];
            //创建动画
            CATransition *animation = [CATransition animation];
            //设置动画类型为立方体动画
            animation.type = @"rippleEffect";
            //设置动画时长
            animation.duration =1.0f;
            //设置运动的方向
            animation.subtype =kCATransitionFromRight;
            //控制器间跳转动画
            [[UIApplication sharedApplication].keyWindow.layer addAnimation:animation forKey:nil];
            [weakSelf presentViewController:tab animated:NO completion:nil];
        } AndFailMessage:^(NSString *message, NSString *errorCode) {
            [SVProgressHUD showErrorWithStatus:message];
        }];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

-(void)creatTimer
{
    if (self.timer == nil) {
        self.timer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(setBtnLabel) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

#pragma mark -计时器事件
-(void)setBtnLabel
{
    if (self.time >0) {
        self.time--;
        NSString * str =[NSString stringWithFormat:@"%ds",self.time];
        [self.codeBtn setTitle:str forState:UIControlStateNormal];
        [self.codeBtn setTitleColor:SFMColor(207, 207, 207) forState:UIControlStateNormal];
    }
    else
    {
        [self.codeBtn setTitle:@"获取" forState:UIControlStateNormal];
        [self.codeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.timer invalidate];
        self.timer = nil;
        self.time = 60;
        self.codeBtn.userInteractionEnabled=YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
